<template>
	<view class="p-30">
		<u--form labelPosition="left" :model="formData" :rules="rules" ref="uForm" labelWidth="100">
			<u-form-item :label="type=='charge'?'充电时间':'更换时间'" prop="time" :required="true">
				<view class="flex justify-between w-100" :class="[formData.time?'':'color-C7C7CC']" @click="dateHandler">
					<view>{{formData.time||'请选择时间'}}</view>
					<u-icon name="arrow-down-fill" color="#C7C7CC"></u-icon>
				</view>
				<u-datetime-picker ref="picker" :show="show" mode="datetime" @confirm="onConfirm"
					@cancel="onCancel"></u-datetime-picker>
			</u-form-item>
			<u-form-item label="电池图片" prop="fileList" :required="true" labelPosition="top">
				<u-upload class="m-t-20" :fileList="formData.fileList" name="img" multiple :maxCount="1"
					:previewFullImage="true" @afterRead="afterRead" @delete="deletePic"></u-upload>
			</u-form-item>
		</u--form>
		<view class="window-bottom">
			<u-button type="primary" text="提交" @click="onSubmit"></u-button>
		</view>
		<u-modal :show="modalShow" :content="content" :showCancelButton="true" @cancel="modalShow=false;"
			@confirm="onDeleteConfirm"></u-modal>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				modalShow: false,
				content: '确认要删除该图片？删除后将无法恢复！',
				type: '',
				show: false,
				info: {},
				formData: {
					fileList: [],
					time: new Date().Format('yyyy-MM-dd hh:mm:ss'),
				},
				form: {
					id: '',
				},
				rules: {
					'time': {
						type: 'string',
						required: true,
						message: '请选择时间',
						trigger: ['blur', 'change']
					},
					'fileList': {
						type: 'array',
						required: true,
						message: '请上传图片',
						trigger: ['blur', 'change']
					},
				},
			}
		},
		onReady() {
			//如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
			this.$refs.uForm.setRules(this.rules)
		},
		onLoad(option) {
			this.getUserInfo()
			this.type = option.type
			this.form.id = option.id
			this.getDeviceDetail()
		},
		methods: {
			// 获取设备详情
			async getDeviceDetail() {
				const res = await this.$api.getDeviceDetailList(this.form.id)
				this.form = res.data
				this.formData.time = new Date().Format('yyyy-MM-dd hh:mm:ss')
				this.$refs.picker.innerValue = this.formData.time
			},
			// 获取登录用户详情
			getUserInfo() {
				const info = uni.getStorageSync('userInfo');
				if (info) {
					this.info = JSON.parse(info)
				}
			},
			dateHandler() {
				this.show = true
			},
			onConfirm(val) {
				this.formData.time = new Date(val.value).Format('yyyy-MM-dd hh:mm:ss')
				this.onCancel()
			},
			onCancel() {
				this.show = false
			},
			onSubmit() {
				this.$refs.uForm.validate().then(res => {
					this.formData[`${this.type}Date`] = this.formData.time
					this.formData[`${this.type}User`] = this.info.id
					let params = Object.assign(this.form, this.formData)
					this.$api.deviceModify(params).then(res => {
						if (res.code === 0) {
							uni.showToast({
								title: '处理成功',
								icon: 'success',
							});
							uni.navigateBack()
						}
					})
				}).catch(errors => {
					uni.$u.toast('校验失败')
				})
			},
			// 删除图片二次确认框
			deletePic(event) {
				this.modalShow = true
				this.deleteEvent = event
			},
			// 删除图片 如果是服务器端的图片择调用删除接口
			async onDeleteConfirm() {
				if (this.deleteEvent.file.fileId) {
					await this.$api.deletupload([this.deleteEvent.file.fileId])
				}
				this.formData.fileList.splice(this.deleteEvent.index, 1)
				this.modalShow = false
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this.formData.fileList.length
				lists.map((item) => {
					this.formData.fileList.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i])
					let item = this.formData.fileList[fileListLen]
					this.formData.fileList.splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			uploadFilePromise(file) {
				let params = {
					'relatedId': this.form.id,
					'rt': this.type,
				}
				this.$api.addupload(params, file).then(res => {
					uni.$u.toast('上传成功')
				}).catch(() => {
					uni.$u.toast('上传失败')
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.u-form-item {
		background-color: #fff;
		padding: 10rpx 30rpx;
		box-shadow: 0rpx 2rpx 15rpx 1rpx rgba(173, 173, 173, 0.1);
		border-radius: 10rpx;
		margin-bottom: 20rpx;
	}
</style>